package com.lht.femalecat.netty.resolve;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @Author:骆宏图
 * @CreateDate: 8:58 2018/7/29.
 * @Description:
 * @Modified By:
 */
public class TimeClient {

    public static void main(String[] args){
        EventLoopGroup group=new NioEventLoopGroup();

        Bootstrap b=new Bootstrap();

        b.group(group).channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                socketChannel.pipeline().addLast(new StringDecoder());
                socketChannel.pipeline().addLast(new ClientHandler());
            }
        });
        try {
            ChannelFuture f=b.connect("127.0.0.1",8080).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }

    }


    private static class ClientHandler extends ChannelInboundHandlerAdapter{

        public static int counter;

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            String content="Query Time Order"+System.getProperty("line.separator");
            byte[] bytes=content.getBytes();

            ByteBuf buf=null;
            for(int i=0;i<100;i++ ){
                buf= Unpooled.buffer(bytes.length);
                buf.writeBytes(bytes);
                ctx.writeAndFlush(buf);
            }
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            String body=(String)msg;
            System.out.println("接受的信息："+body+",数量："+ ++counter);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    }
}
